<template>
  <div class="detail">
    <Header />

    <a-spin :spinning="loading" style="min-height: 200px">
      <div class="detail-content">
        <div class="detail-content-bottom">
          <div class="thing-content-view">
            <div class="main-content">
              <div style="text-align: center;font-size: 18px;color:#111;font-weight:bold;margin: 20px 0;">{{detailData.title}}</div>
              <div style="text-align: center;font-size: 14px;color:#111;margin: 20px 0;">来源：{{detailData.source}}&nbsp;&nbsp;发布时间：{{getFormatTime(detailData.createTime, true)}}</div>
              <div class="description" v-html="detailData.description" style="margin: 30px 0; "></div>
              <div class="more" style="align-items: center;justify-content: center;margin: 40px 0;">
                <div class="btn-like" @click="addToWish()" :class="{ 'liked': isLiked }">
                  <img :src="WantIcon" style="padding: 3px" />
                  <div class="label">点赞（{{ detailData.likeCount }}）</div>
                </div>
                <div class="btn-like" @click="collect()" :class="{ 'collected': isCollected }">
                  <img :src="RecommendIcon" />
                  <div class="label">收藏（{{ detailData.collectCount }}）</div>
                </div>
                <div class="btn-like" @click="share()">
                  <img :src="ShareIcon" />
                  <div class="label">分享</div>
                </div>
              </div>
              <a-tabs>
                <a-tab-pane key="1" tab="评论">
                  <!--评论-->
                  <div class="thing-comment" :class="selectTabIndex > 0 ? '' : 'hide'">
                    <div class="title">发表新的评论</div>
                    <div class="publish flex-view">
                      <img :src="AvatarIcon" class="mine-img" />
                      <input placeholder="说点什么..." class="content-input" ref="commentRef" />
                      <button class="send-btn" @click="sendComment()">发送</button>
                    </div>
                    <div class="tab-view flex-view">
                      <div class="count-text">共有{{ commentData.length }}条评论</div>
                      <div class="tab-box flex-view" v-if="commentData.length > 0">
                        <span :class="sortIndex === 0 ? 'tab-select' : ''" @click="sortCommentList('recent')">最新</span>
                        <div class="line"></div>
                        <span :class="sortIndex === 1 ? 'tab-select' : ''" @click="sortCommentList('hot')">热门</span>
                      </div>
                    </div>
                    <div class="comments-list">
                      <div class="comment-item" v-for="item in commentData">
                        <div class="flex-item flex-view">
                          <img :src="item.avatar || AvatarIcon" class="avator" />
                          <div class="person">
                            <div class="name">{{ item.username }}</div>
                            <div class="time">{{ item.commentTime }}</div>
                          </div>
                          <div class="float-right">
                            <span @click="like(item.id)">推荐</span>
                            <span class="num">{{ item.likeCount }}</span>
                          </div>
                        </div>
                        <p class="comment-content">{{ item.content }}</p>
                      </div>
                      <div class="infinite-loading-container">
                        <div class="infinite-status-prompt" style="">
                          <div slot="no-results" class="no-results">
                            <div></div>
                            <p>没有更多了</p>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </a-tab-pane>
              </a-tabs>
            </div>
            <div class="main-side">
              <div class="recommend" style="min-height: 300px">
                <div class="title">相关推荐</div>
                <div class="things">
                  <div class="thing-item" v-for="item in recommendData" @click="handleDetail(item)">
                    <div class="img-view"> <img :src="item.cover" /></div>
                    <div class="info-view">
                      <h3 class="thing-name">{{ item.title.substring(0, 12) }}</h3>
                      <span>
                        <span class="a-price-symbol"></span>
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </a-spin>

    <Footer />
  </div>
</template>
<script setup>
  import { ref, reactive, onMounted } from 'vue';
  import { message } from 'ant-design-vue';
  import Header from '/@/views/index/components/header.vue';
  import Footer from '/@/views/index/components/footer.vue';
  import WantIcon from '/@/assets/images/want-read-hover.png';
  import RecommendIcon from '/@/assets/images/recommend-hover.png';
  import ShareIcon from '/@/assets/images/share-icon.svg';
  import AvatarIcon from '/@/assets/images/avatar.jpg';

  import { detailApi, getRecommendApi } from '/@/api/thing';
  import { listThingCommentsApi, createApi as createCommentApi, likeApi } from '/@/api/comment';
  import { wishApi, checkWishApi } from '/@/api/thingWish';
  import { collectApi, checkCollectApi } from '/@/api/thingCollect';
  import { BASE_URL } from '/@/store/constants';
  import { useRoute, useRouter } from 'vue-router/dist/vue-router';
  import { useUserStore } from '/@/store';
  import { getFormatTime } from '/@/utils';


  let loading = ref(false);

  const router = useRouter();
  const route = useRoute();
  const userStore = useUserStore();

  let thingId = ref('');
  let detailData = ref({});
  let selectTabIndex = ref('1');

  let commentData = ref([]); // 评论数据
  let recommendData = ref([]); // 推荐数据
  let adData = ref([]); // 广告数据
  let sortIndex = ref(0);
  let order = ref('recent'); // 默认排序最新
  let isLiked = ref(false); // 是否已点赞
  let isCollected = ref(false); // 是否已收藏

  let commentRef = ref();

  onMounted(() => {
    thingId.value = route.query.id.trim();
    getThingDetail();
    getRecommendThing();
    getCommentList();
    checkUserStatus();
  });

  const getThingDetail = () => {
    loading.value = true;
    detailApi({ id: thingId.value })
      .then((res) => {
        loading.value = false;
        detailData.value = res.data;
        detailData.value.cover = BASE_URL + '/api/staticfiles/image/' + detailData.value.cover + '?t=' + new Date().getTime();
        
        // 处理新闻内容中的图片路径
        if (detailData.value.description) {
          detailData.value.description = processContentImages(detailData.value.description);
        }
      })
      .catch((err) => {
        message.error('获取详情失败');
      });
  };
  
  // 处理内容中的图片路径
  const processContentImages = (content) => {
    if (!content) return content;
    
    // 替换相对路径的图片为完整路径
    return content.replace(
      /<img([^>]*)src=["']([^"']+)["']([^>]*)>/gi,
      (match, before, src, after) => {
        // 如果图片路径不是以http开头，则添加BASE_URL
        if (!src.startsWith('http') && !src.startsWith('data:')) {
          if (src.startsWith('/')) {
            src = BASE_URL + src;
          } else {
            src = BASE_URL + '/api/staticfiles/image/' + src;
          }
        }
        return `<img${before}src="${src}?t=${new Date().getTime()}"${after}>`;
      }
    );
  };
  const addToWish = () => {
    let userId = userStore.user_id;
    if (userId) {
      wishApi({ thingId: thingId.value, userId: userId })
        .then((res) => {
          message.success(res.msg);
          isLiked.value = !isLiked.value; // 切换状态
          getThingDetail(); // 刷新数据
        })
        .catch((err) => {
          console.log('操作失败');
        });
    } else {
      message.warn('请先登录');
    }
  };
  const collect = () => {
    let userId = userStore.user_id;
    if (userId) {
      collectApi({ thingId: thingId.value, userId: userId })
        .then((res) => {
          message.success(res.msg);
          isCollected.value = !isCollected.value; // 切换状态
          getThingDetail(); // 刷新数据
        })
        .catch((err) => {
          console.log('收藏失败');
        });
    } else {
      message.warn('请先登录');
    }
  };
  const share = () => {
    let content = '分享一个非常好玩的网站 ' + window.location.href;
    let shareHref = 'http://service.weibo.com/share/share.php?title=' + content;
    window.open(shareHref);
  };

  const getRecommendThing = () => {
    getRecommendApi({ excludeId: thingId.value })
      .then((res) => {
        res.data.forEach((item, index) => {
          if (item.cover) {
            item.cover = BASE_URL + '/api/staticfiles/image/' + item.cover + '?t=' + new Date().getTime();
          }
        });
        console.log(res);
        recommendData.value = res.data.slice(0, 12);
      })
      .catch((err) => {
        console.log(err);
      });
  };

  const checkUserStatus = () => {
    let userId = userStore.user_id;
    if (userId) {
      // 检查是否已点赞
      checkWishApi({ userId: userId, thingId: thingId.value })
        .then((res) => {
          isLiked.value = res.data;
        })
        .catch((err) => {
          console.log(err);
        });
      
      // 检查是否已收藏
      checkCollectApi({ userId: userId, thingId: thingId.value })
        .then((res) => {
          isCollected.value = res.data;
        })
        .catch((err) => {
          console.log(err);
        });
    }
  };
  const handleDetail = (item) => {
    // 跳转新页面
    let text = router.resolve({ name: 'detail', query: { id: item.id } });
    window.open(text.href, '_blank');
  };

  const sendComment = () => {
    console.log(commentRef.value);
    let text = commentRef.value.value.trim();
    console.log(text);
    if (text.length <= 0) {
      return;
    }
    commentRef.value.value = '';
    let userId = userStore.user_id;
    if (userId) {
      createCommentApi({ content: text, thingId: thingId.value, userId: userId })
        .then((res) => {
          getCommentList();
        })
        .catch((err) => {
          console.log(err);
        });
    } else {
      message.warn('请先登录！');
      router.push({ name: 'login' });
    }
  };
  const like = (commentId) => {
    likeApi({ id: commentId })
      .then((res) => {
        getCommentList();
      })
      .catch((err) => {
        console.log(err);
      });
  };
  const getCommentList = () => {
    listThingCommentsApi({ thingId: thingId.value, order: order.value })
      .then((res) => {
        res.data.forEach((item) => {
          item.commentTime = getFormatTime(item.createTime, true);
          if(item.cover){
            item.avatar = BASE_URL + '/api/staticfiles/avatar/' + item.cover;
          }
        });
        commentData.value = res.data;
      })
      .catch((err) => {
        console.log(err);
      });
  };
  const sortCommentList = (sortType) => {
    if (sortType === 'recent') {
      sortIndex.value = 0;
    } else {
      sortIndex.value = 1;
    }
    order.value = sortType;
    getCommentList();
  };
</script>
<style lang="less">

// 全局样式：处理新闻内容中的图片
:deep(.description) {
  img {
    max-width: 100% !important;
    height: auto !important;
    display: block !important;
    margin: 10px auto !important;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;
    transition: all 0.3s ease !important;
  }
  
  p {
    line-height: 1.8 !important;
    margin: 16px 0 !important;
    color: #333 !important;
    font-size: 16px !important;
  }
  
  h1, h2, h3, h4, h5, h6 {
    margin: 20px 0 12px 0 !important;
    color: #152844 !important;
    font-weight: 600 !important;
  }
  
  ul, ol {
    padding-left: 20px !important;
    margin: 16px 0 !important;
    
    li {
      margin: 8px 0 !important;
      line-height: 1.6 !important;
    }
  }
  
  blockquote {
    border-left: 4px solid #4684e2 !important;
    padding-left: 16px !important;
    margin: 16px 0 !important;
    color: #666 !important;
    font-style: italic !important;
    background: #f8f9fa !important;
    padding: 12px 16px !important;
    border-radius: 4px !important;
  }
  
  table {
    width: 100% !important;
    border-collapse: collapse !important;
    margin: 16px 0 !important;
    
    th, td {
      border: 1px solid #ddd !important;
      padding: 8px 12px !important;
      text-align: left !important;
    }
    
    th {
      background: #f5f5f5 !important;
      font-weight: 600 !important;
    }
  }
}

// 兼容
@media screen and (max-width: 720px) {
  .detail-content {
    width: 90% !important;
  }
  .top-left-img {
    width: 99% !important;
  }
  .main-side {
    width: 100% !important;
  }
  .more {
    display: none !important;
  }
  
  // 移动端图片样式优化
  :deep(.description) {
    img {
      max-width: 100% !important;
      height: auto !important;
      margin: 8px auto !important;
    }
    
    p {
      font-size: 14px !important;
      line-height: 1.6 !important;
      margin: 12px 0 !important;
    }
    
    h1, h2, h3, h4, h5, h6 {
      font-size: 16px !important;
      margin: 16px 0 8px 0 !important;
    }
  }
}

.detail {
  background: #ebf7f8;
  padding-top: 100px;
}

.detail-content {
  display: flex;
  flex-direction: column;
  width: 70%;
  margin: 0 auto;
}

.thing-content-view {
  padding-bottom: 50px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  gap: 30px;
}

.main-content {
  flex: 1;
  min-width: 300px;
  padding: 0 16px;

  background: #fff;
  border-radius: 2px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

  .text {
    color: #484848;
    font-size: 16px;
    line-height: 26px;
    padding-left: 12px;
    margin: 11px 0;
    white-space: pre-wrap;
  }

  .description{
    min-height: 300px;
    
    // 图片自适应样式
    img {
      max-width: 100%;
      height: auto;
      display: block;
      margin: 10px auto;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;
    }
    
    // 确保内容区域有合适的行高和间距
    p {
      line-height: 1.8;
      margin: 16px 0;
      color: #333;
      font-size: 16px;
    }
    
    // 标题样式
    h1, h2, h3, h4, h5, h6 {
      margin: 20px 0 12px 0;
      color: #152844;
      font-weight: 600;
    }
    
    // 列表样式
    ul, ol {
      padding-left: 20px;
      margin: 16px 0;
      
      li {
        margin: 8px 0;
        line-height: 1.6;
      }
    }
    
    // 引用样式
    blockquote {
      border-left: 4px solid #4684e2;
      padding-left: 16px;
      margin: 16px 0;
      color: #666;
      font-style: italic;
      background: #f8f9fa;
      padding: 12px 16px;
      border-radius: 4px;
    }
    
    // 表格样式
    table {
      width: 100%;
      border-collapse: collapse;
      margin: 16px 0;
      
      th, td {
        border: 1px solid #ddd;
        padding: 8px 12px;
        text-align: left;
      }
      
      th {
        background: #f5f5f5;
        font-weight: 600;
      }
    }
  }


  .more {
    display: flex;
    flex-direction: row;
    gap: 16px;
    .btn-like {
      white-space: nowrap;
      display: flex;
      flex-direction: row;
      cursor: pointer;
      transition: all 0.3s ease;
      
      &.liked {
        color: #ff6b35;
        .label {
          color: #ff6b35;
        }
      }
      
      &.collected {
        color: #ffd700;
        .label {
          color: #ffd700;
        }
      }
      
      img {
        width: 20px;
        height: 20px;
        object-fit: fill;
      }
      .label {
        font-size: 14px;
        color: #777;
      }
    }
  }

  .thing-comment {
    .title {
      font-weight: 600;
      font-size: 14px;
      line-height: 22px;
      height: 22px;
      color: #152844;
      margin: 24px 0 12px;
    }

    .publish {
      align-items: center;

      .mine-img {
        -webkit-box-flex: 0;
        -ms-flex: 0 0 40px;
        flex: 0 0 40px;
        margin-right: 12px;
        border-radius: 50%;
        width: 40px;
        height: 40px;
      }

      .content-input {
        flex: 1;
        background: #f6f9fb;
        border-radius: 4px;
        min-width: 100px;
        height: 32px;
        line-height: 32px;
        color: #484848;
        padding: 5px 12px;
        white-space: nowrap;
        outline: none;
        border: 0px;
      }

      .send-btn {
        margin-left: 10px;
        width: 80px;
        background: #4684e2;
        border-radius: 4px;
        color: #fff;
        font-size: 14px;
        text-align: center;
        height: 32px;
        line-height: 32px;
        outline: none;
        border: 0px;
        cursor: pointer;
      }
    }

    .tab-view {
      -webkit-box-pack: justify;
      -ms-flex-pack: justify;
      justify-content: space-between;
      font-size: 14px;
      -webkit-box-align: center;
      -ms-flex-align: center;
      align-items: center;
      margin: 24px 0;

      .count-text {
        color: #484848;
        float: left;
      }

      .tab-box {
        color: #5f77a6;
        -webkit-box-align: center;
        -ms-flex-align: center;
        align-items: center;

        .tab-select {
          color: #152844;
        }

        span {
          cursor: pointer;
        }
      }

      .line {
        width: 1px;
        height: 12px;
        margin: 0 12px;
        background: #cedce4;
      }
    }
  }

  .comments-list {
    .comment-item {
      .flex-item {
        -webkit-box-align: center;
        -ms-flex-align: center;
        align-items: center;
        padding-top: 16px;

        .avator {
          -webkit-box-flex: 0;
          -ms-flex: 0 0 40px;
          flex: 0 0 40px;
          width: 40px;
          height: 40px;
          margin-right: 12px;
          border-radius: 50%;
          cursor: pointer;
        }

        .person {
          -webkit-box-flex: 1;
          -ms-flex: 1;
          flex: 1;
        }

        .name {
          color: #152844;
          font-weight: 600;
          font-size: 14px;
          line-height: 22px;
          height: 22px;
          cursor: pointer;
        }

        .time {
          color: #5f77a6;
          font-size: 12px;
          line-height: 16px;
          height: 16px;
          margin-top: 2px;
        }

        .float-right {
          color: #4684e2;
          font-size: 14px;
          float: right;

          span {
            margin-left: 19px;
            cursor: pointer;
          }

          .num {
            color: #152844;
            margin-left: 6px;
            cursor: auto;
          }
        }
      }
    }
  }

  .comment-content {
    margin-top: 8px;
    color: #484848;
    font-size: 14px;
    line-height: 22px;
    padding-bottom: 16px;
    border-bottom: 1px dashed #cedce4;
    margin-left: 52px;
    overflow: hidden;
    word-break: break-word;
  }
}

.main-side {
  width: 220px;

  .recommend {
    background: #fff;
    border-radius: 2px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

    .title {
      font-weight: 600;
      font-size: 16px;
      height: 48px;
      line-height: 48px;
      padding-left: 16px;
      color: #152844;

      border-bottom: 1px solid #eee;
    }

    .things {
      display: flex;
      flex-direction: column;
      gap: 16px;
      padding: 20px 0;

      .thing-item {
        width: 85%;
        margin: 0px auto;
        position: relative;
        cursor: pointer;

        .img-view {
          width: 100%;
          img {
            border-radius: 8px;
            width: 100%;
            aspect-ratio: 5/3;
            background-size: cover;
            object-fit: cover;
          }
        }

        .info-view {
          //background: #f6f9fb;
          overflow: hidden;
          .thing-name {
            margin-top: 12px;
            color: #0f1111;
            font-size: 14px;
          }

          .price {
            color: #ff7b31;
            font-size: 20px;
            line-height: 20px;
            margin-top: 4px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
      }
    }
  }
}

.flex-view {
  display: flex;
}
</style>
